﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region Using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Drawing;
using System.Configuration;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ServiceModel;
using NetBay.Core.Extensions;
using NetBay.Core.BusinessEntities;
using Rio.Windows.Services.BusinessLayer;
#endregion

namespace RioWCFandWindowsServices
{
    /// <summary>
    /// Class that handles RioWindowsServices
    /// </summary>
    public partial class RioWCFWindowsServices : ServiceBase
    {
        #region Members
        System.Timers.Timer l_oAlertTimer = new System.Timers.Timer();
        #endregion

        #region Main
        public static void Main()
        {
//#if (!DEBUG)
                ServiceBase.Run(new RioWCFWindowsServices());
//#else
//            RioWCFWindowsServices l_lDebugTest = new RioWCFWindowsServices();
//            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
//#endif
        }
        #endregion

        #region Private members
        
        private static int m_lAlertCheckEvery;
        public static int AlertCheckEvery
        {
            get { return RioWCFWindowsServices.m_lAlertCheckEvery; }
        }
        
        private static string m_sSmtpServer = string.Empty;
        public static string SmtpServer
        {
            get { return RioWCFWindowsServices.m_sSmtpServer; }
        }

        private static string m_sSmtpLogin = string.Empty;
        public static string SmtpLogin
        {
            get { return RioWCFWindowsServices.m_sSmtpLogin; }
        }

        private static string m_sSmtpPassword = string.Empty;
        public static string SmtpPassword
        {
            get { return RioWCFWindowsServices.m_sSmtpPassword; }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public RioWCFWindowsServices()
        {
            try
            {
                InitializeComponent();

                NetBay.Core.Log.LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.Windows.Services.Configuration"));

                if (CheckParametersValues())
                {
                    InitParameters();

                    NetBay.Core.Log.LogManager.Instance().LogInfo("<<<<<<<<<<<<<<<<<<<<<<<< LAUNCHING SERVICE RIO.WINDOS.SERVICE >>>>>>>>>>>>>>>>>>>>>>" + DateTime.Now);

                    //Getting the parameters from the configuration file
                    NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                    NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                    NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                    NetBay.Core.Log.LogManager.Instance().LogInfo("Parameters missing check--------------------------- " + DateTime.Now);
                    if (CheckMissingParameters())
                    {
                        //Getting the parameters from the configuration file
                        NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                        NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                        NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                        NetBay.Core.Log.LogManager.Instance().LogInfo("Database checking --------------------------- " + DateTime.Now);

                        if (CheckDatabase())
                        {
                            StartAlertTimer();
                        }
                        else
                        {
                            NetBay.Core.Log.LogManager.Instance().LogInfo("----------------ERROR ------- Database Failure --------------------------- " + DateTime.Now);
                        }
                    }
                    else
                    {
                        NetBay.Core.Log.LogManager.Instance().LogInfo("----------------ERROR ------- Parameters missing error --------------------------- " + DateTime.Now);
                    }
                }
                else
                {
                    NetBay.Core.Log.LogManager.Instance().LogInfo("--------------ERROR ------- Invalid Parameters value--------------------------- " + DateTime.Now);
                }
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN RioWindowsServices() EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
        }

        #endregion

        #region Methods

        #region Private

        /// <summary>
        /// Service OnStart
        /// </summary>
        /// <param name="args">Args on the startup</param>
        protected override void OnStart(string[] args)
        {
            #region Code pour incorporer les service wcf dans le service windows
            NetBay.Core.Log.LogManager.Instance().LogInfo("<<<<<<<<<<<<<<<<<<<<<<<< Starting Service Rio.Windows.Service >>>>>>>>>>>>>>>>>>>>>> " + DateTime.Now);
            #endregion
        }

        /// <summary>
        /// Service OnStop
        /// </summary>
        protected override void OnStop()
        {
            #region Code pour incorporer les service wcf dans le service windows
            NetBay.Core.Log.LogManager.Instance().LogInfo("<<<<<<<<<<<<<<<<<<<<<<<< Stopping Service Rio.Windows.Service >>>>>>>>>>>>>>>>>>>>>> " + DateTime.Now);
            #endregion
        }

        /// <summary>
        /// Check if the database is online
        /// </summary>
        /// <returns>True if database is ok</returns>
        private bool CheckDatabase()
        {
            #region CheckDatabase
            BusinessLayer.InitDatabase(Application.StartupPath, new FileInfo(ConfigurationManager.AppSettings.Get("Rio.Windows.Services.Configuration")).Name, ConfigurationManager.AppSettings.Get("Rio.Windows.Services.DataBaseConnection"));
            return BusinessLayer.IsDataBaseOnline();
            #endregion
        }

        /// <summary>
        /// Checking the parameters values
        /// </summary>
        /// <returns>False if one of the parameters is wrong</returns>
        private bool CheckParametersValues()
        {
            Boolean l_bParameterOK = true;
            int l_iOutTry = int.MaxValue;
                
            try
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo("----- Rio.Windows.Services.Configuration value [" + ConfigurationManager.AppSettings.Get("Rio.Windows.Services.Configuration") + "]");
                if (!new FileInfo(ConfigurationManager.AppSettings.Get("Rio.Windows.Services.Configuration")).Exists)
                {
                    l_bParameterOK = false;
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- File does not exists ");
                }
                else
                    NetBay.Core.Log.LogManager.Instance().LogInfo("-------- OK ");

                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo("----- Rio.Windows.Services.AlertCheckEvery value [" + ConfigurationManager.AppSettings.Get("Rio.Windows.Services.AlertCheckEvery") + "]");
                l_iOutTry = int.MaxValue;
                if (!(Int32.TryParse(ConfigurationManager.AppSettings.Get("Rio.Windows.Services.AlertCheckEvery"), out l_iOutTry)))
                {
                    l_bParameterOK = false;
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Rio.Windows.Services.AlertCheckEvery is not numeric ");
                }
                else
                    NetBay.Core.Log.LogManager.Instance().LogInfo("-------- OK ");
            }
            catch (Exception ex)
            {
                l_bParameterOK = false;
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CheckParameters() EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            return l_bParameterOK;
        }

        /// <summary>
        /// Checking if all parameters are present
        /// </summary>
        /// <returns>False if one of the parameters is missing</returns>
        private bool CheckMissingParameters()
        {
            Boolean l_bParameterOK = true;
            try
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo("----- Rio.Windows.Services.DataBaseConnection");
                
                if ( ConfigurationManager.AppSettings.Get("Rio.Windows.Services.DataBaseConnection") == null)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Parameter Rio.Windows.Services.DataBaseConnection missing ");
                    l_bParameterOK = false;
                }


                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo("----- Rio.Windows.Services.SmTpServer ");

                if (ConfigurationManager.AppSettings.Get("Rio.Windows.Services.SmTpServer") == null)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Parameter Rio.Windows.Services.SmTpServer missing ");
                    l_bParameterOK = false;
                }

                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo("----- Rio.Windows.Services.AlertCheckEvery ");
                if (ConfigurationManager.AppSettings.Get("Rio.Windows.Services.AlertCheckEvery") == null)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Parameter Rio.Windows.Services.AlertCheckEvery missing ");
                    l_bParameterOK = false;
                }

                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo("----- Rio.Windows.Services.Configuration ");
                if (ConfigurationManager.AppSettings.Get("Rio.Windows.Services.Configuration") == null)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Parameter Rio.Windows.Services.Configuration missing ");
                    l_bParameterOK = false;
                }
            }
            catch (Exception ex)
            {
                l_bParameterOK = false;
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CheckParameters() EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            return l_bParameterOK;
        }

        /// <summary>
        /// Getting the parameters form the configuration file
        /// </summary>
        private void InitParameters()
        {
            NetBay.Core.Log.LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.Windows.Services.Configuration"));
            m_lAlertCheckEvery = Convert.ToInt32(ConfigurationManager.AppSettings.Get("Rio.Windows.Services.AlertCheckEvery"));
            m_sSmtpServer = ConfigurationManager.AppSettings.Get("Rio.Windows.Services.SmTpServer");
            m_sSmtpLogin = ConfigurationManager.AppSettings.Get("Rio.Windows.Services.SmTpLogin");
            m_sSmtpPassword = ConfigurationManager.AppSettings.Get("Rio.Windows.Services.SmTpPassword");
        }

        /// <summary>
        /// Starting the alert timer
        /// </summary>
        private void StartAlertTimer()
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            NetBay.Core.Log.LogManager.Instance().LogInfo("----- Starting the alert timer. Check every [" + m_lAlertCheckEvery + "] minute(s) --------------------------- " + DateTime.Now);


            l_oAlertTimer.Elapsed += new System.Timers.ElapsedEventHandler(l_oAlertTimer_Elapsed);
            l_oAlertTimer.Interval = m_lAlertCheckEvery * 60 * 1000;
            l_oAlertTimer.Start();
        }

        /// <summary>
        /// Event on all Alert Timer Tick
        /// </summary>
        private void l_oAlertTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            l_oAlertTimer.Stop();
            NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            NetBay.Core.Log.LogManager.Instance().LogInfo("----- New alert tick at : " + DateTime.Now);
            try
            {
                BusinessLayer.SendAlerts(SmtpServer, SmtpLogin, SmtpPassword);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo("----- Exception in l_oAlertTimer_Tick. Exception [" + ex.Message + "]" + DateTime.Now);
            }
            l_oAlertTimer.Start();
            NetBay.Core.Log.LogManager.Instance().LogInfo("----- End of alert tick at : " + DateTime.Now);
        }

        #endregion

        #endregion
    }
}
